#include "MysqlStatement.h"
#include "exception/SQLException.h"

using namespace std;
using namespace mysql;

MysqlStatement::MysqlStatement(MYSQL *conn) :
        conn_(conn), stmt_(mysql_stmt_init(conn)) {
    if (!stmt_) {
        throw SQLException("Could not initialize statement", mysql_errno(conn), mysql_error(conn));
    }
}

bool MysqlStatement::execute(const string &sql) {
    if (mysql_stmt_prepare(stmt_, sql.c_str(), sql.size())) {
        throw SQLException("Query preparation failed", mysql_stmt_errno(stmt_), mysql_stmt_error(stmt_));
    }
    if (mysql_stmt_execute(stmt_)) {
        throw SQLException("Query execution failed", mysql_stmt_errno(stmt_), mysql_stmt_error(stmt_));
    }
    return true;
}

MysqlResult MysqlStatement::executeQuery(const string &sql) {
    execute(sql);
    return MysqlResult(stmt_);
}
